package cn.zhentao.controller;

import cn.zhentao.common.Result;
import cn.zhentao.dtos.ResponseResult;
import cn.zhentao.service.FileStorageService;
import cn.zhentao.service.TUserService;
import cn.zhentao.user.dto.LoginDto;
import cn.zhentao.user.pojo.TUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Random;

/**
 * 用户控制层
 */
@RestController
public class TUserContro {
    @Autowired
    private TUserService tUserService;
    @Autowired
    private FileStorageService fileStorageService; //上传头像

    //用户登录
    @PostMapping("login")
    public ResponseResult login(@RequestBody LoginDto dto){
        return tUserService.login(dto);
    }

    //登录后的个人信息返回
    @GetMapping("userinfo")
    public ResponseResult userinfo(){
        TUser info = tUserService.info();
        return ResponseResult.okResult(info);
    }

    //用户注册
    @PostMapping("regiest")
    public ResponseResult regiest(@RequestBody TUser tUser){
        ResponseResult regiest = tUserService.regiest(tUser);
        return regiest;
    }
    //判断用户是否重复
    @GetMapping("user_exist")
    public ResponseResult user_exist(String phone){
        TUser one = tUserService.getOne(Wrappers.<TUser>lambdaQuery().eq(TUser::getPhone,phone));
        if(one == null){
            return ResponseResult.okResult(200);
        }else{
            return ResponseResult.errorResult(500, "已有该账户");
        }
    }

    //用户上传头像
    @PostMapping("avatar_submit")
    public Result avatar_submit(MultipartFile file) throws IOException {
//        int i = new Random().nextInt(9999);
        String path = fileStorageService.uploadImgFile("", file.getOriginalFilename(), file.getInputStream());
//        String avatarname=path+i;
        System.out.println("头像======>"+path);

        TUser info = tUserService.info();
        System.out.println(info);
        if(info !=null){
            info.setAvatar(path);
            tUserService.updateById(info);
        }
        return Result.OK(path);
    }

    //用户修改
    @PostMapping("update_user")
    public ResponseResult update_user(@RequestBody TUser tUser){
       return tUserService.update_user(tUser);
    }

    //获取验证码
    @GetMapping("/Code_request")  //Code_request
    public void code(@RequestParam("phone") String phone){
       tUserService.Code_request(phone);
    }
}
